package com.example.test_flutter.channel

import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.*
import java.nio.ByteBuffer

class FlutterBridge(protected val engine: FlutterEngine) {

    companion object {
        const val channelKey = "FlutterBridge";
    }

    val methodChannel: MethodChannel by lazy {
        MethodChannel(engine.dartExecutor, channelKey)
    }

    val eventChannel: EventChannel by lazy {
        EventChannel(engine.dartExecutor, channelKey)
    }

    //发送String类型消息
    val messageChannelString: BasicMessageChannel<String> by lazy {
        BasicMessageChannel(engine.dartExecutor.binaryMessenger, channelKey, StringCodec.INSTANCE)
    }

    //发送Json格式消息
    val messageChannelJson: BasicMessageChannel<Any> by lazy {
        BasicMessageChannel(
            engine.dartExecutor.binaryMessenger,
            channelKey,
            JSONMessageCodec.INSTANCE
        )
    }

    //发送基本型数据
    val messageChannelStandard: BasicMessageChannel<Any> by lazy {
        BasicMessageChannel(
            engine.dartExecutor.binaryMessenger,
            channelKey,
            StandardMessageCodec.INSTANCE
        )
    }

    //发送二进制消息 图片 视频等
    val messageChannelByteBuffer: BasicMessageChannel<ByteBuffer> by lazy {
        BasicMessageChannel(engine.dartExecutor.binaryMessenger, channelKey, BinaryCodec.INSTANCE)
    }

    private val methodsMap = mutableMapOf<String, ((Any) -> Any)?>()

    init {
        methodChannel.setMethodCallHandler { call, result ->
            methodsMap[call.method]?.also {
                result.success(it.invoke(call.arguments))
            }
        }
    }

    fun <Params : Any, Return : Any> register(method: String, block: (Params) -> Return) {
        methodsMap[method] = block as (Any) -> Any
    }

    fun <Params : Any> invoke(method: String, params: Params, block: MethodChannel.Result) {
        methodChannel.invokeMethod(method, params, block)
    }


}
